package com.markhsiu.framework.netty;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeServerHandler extends ChannelInboundHandlerAdapter{

	private ByteBuf buf;
	
	
	//解决TCP/IP 粘包问题
	//1 发送端需要等缓冲区满才发送出去，造成粘包
	//2 接收方不及时接收缓冲区的包，造成多个包接收
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		buf = ctx.alloc().buffer(4);
	}
	
	@Override 
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		buf.release();
		buf = null;
	}
	
	
	@Override 
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf m = (ByteBuf)msg;
		buf.writeBytes(m);
		m.release();
		
		if(buf.readableBytes() >= 4){
			long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L;
			System.out.println(new Date(currentTimeMillis));
			ctx.close();
		}
	}
	
	
	@Override
    public void channelActive(final ChannelHandlerContext ctx){
//		final ByteBuf time = ctx.alloc().buffer(4);
//		time.writeInt((int)(System.currentTimeMillis()/1000L + 2208988800l));
//		
//		final ChannelFuture f = ctx.writeAndFlush(time);
//		//f.addListener(ChannelFutureListener.CLOSE);
//		f.addListener(new ChannelFutureListener() {
//			
//			@Override
//			public void operationComplete(ChannelFuture future) throws Exception {
//				assert f == future;
//				//close the connection
//				ctx.close();
//			}
//		});
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
}
